package com.xiaoshu.test.rpc.netty.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 
 * @author ubt
 *
 */
public class InvokerHandler extends ChannelInboundHandlerAdapter {
	
	private ConcurrentHashMap<String , Object> clazzMap = new ConcurrentHashMap<>();

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    	ctx.flush();
    	ctx.close();
    }
	
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    	
    	ClassInfo classInfo = (ClassInfo)msg;
    	Object clazz = null;
    	if(!clazzMap.containsKey(classInfo.getClassName())){
    		clazz = Class.forName(classInfo.getClassName()).newInstance();
    		clazzMap.put(classInfo.getClassName(), clazz);
    	}else{
    		clazz = clazzMap.get(classInfo.getClassName());
    	}
    	
    	Method method = clazz.getClass().getMethod(classInfo.getMethodName(), classInfo.getParameterTypes());
    	Object result = method.invoke(clazz, classInfo.getArgs());
    	ctx.write(result);
    }
    
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
    	cause.printStackTrace();
    	ctx.close();
    }
}
